﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using LynxWiki.DomainModel;
using LynxWiki.Filters;
using LynxWiki.Search;
using LynxWiki.ViewModels;
using LynxWiki.Repository;

namespace LynxWiki.Controllers
{
    [InitializeSimpleMembership]
    public class WikiDirectoryController : Controller
    {
        //
        // GET: /WikiDirectory/

        [TopicActionFilter]
        public ActionResult Index(string fullPath)
        {
            WikiDirectoryRepository wikiDirRep = new WikiDirectoryRepository(Server.MapPath(fullPath));
            WikiDirectory wikiDir = wikiDirRep.GetWikiDirectoryInfo(Server.MapPath(fullPath));
            WikiDirectoryViewData wDirData = new WikiDirectoryViewData(wikiDir);
            wDirData.WikiDirs = wikiDirRep.GetSubDirectoryList().ToList();
            wDirData.cntWikiDirs = wDirData.WikiDirs.Count();
            List<WikiTopicListingViewData> wtlvd = new List<WikiTopicListingViewData>();
            List<FileInfo> fi = wikiDirRep.GetWikiTopicFileInfoList();
            foreach (FileInfo file in fi) {
                WikiTopicListingViewData wtl = new WikiTopicListingViewData();
                if (wikiDir.RootDirectory.Contains(wikiDir.DirectoryName)) {
                    wtl.WikiDir = wikiDir.RootDirectory.Replace("\\", "/");
                }
                else {
                    wtl.WikiDir = (wikiDir.RootDirectory + "/" + wikiDir.DirectoryName).Replace("\\", "/");
                }
                wtl.TopicName = file.Name.Substring(0, file.Name.IndexOf("_current.xml") - 1);
                wtl.CreatedOn = file.LastWriteTime;
                wtl.TopicLocked = wikiDirRep.TopicIsLocked(file.Name);
                wtlvd.Add(wtl);
            }
            wDirData.TopicListing = wtlvd;
            wDirData.cntTopicNames = wDirData.TopicListing.Count();
            HttpContext.Session["__MyWorkingDir"] = new WorkingDirectory(Server.MapPath(fullPath));

            return View(wDirData);
        }

        //
        // GET: /WikiDirectory/Details/5
        [TopicActionFilter]
        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /WikiDirectory/Create
        [TopicActionFilter]
        public ActionResult Create()
        {
            ViewBag.CurrentDir = ((WorkingDirectory)this.GetMySessionObject("__MyWorkingDir")).WorkingDir;
            WikiDirectoryViewData wDirData = new WikiDirectoryViewData();
            wDirData.RootDirectory = WikiRoot.RootDirectory;
            wDirData.ParentPath = ViewBag.CurrentDir;
            return View(wDirData);
        }

        //
        // POST: /WikiDirectory/Create

        [HttpPost, ValidateAntiForgeryToken]
        [TopicActionFilter]
        public ActionResult Create(WikiDirectoryViewData wDirData)
        {
            WorkingDirectory wd = (WorkingDirectory)this.GetMySessionObject("__MyWorkingDir");
            try
            {
                if (wDirData.ParentPath == null)
                    wDirData.ParentPath = string.Empty;
                WikiDirectoryRepository wikiDirRep = new WikiDirectoryRepository(wd.WorkingDir);
                string userName = User.Identity.Name;
                if (string.IsNullOrEmpty(userName)) {
                    userName = Request.UserHostAddress;
                }
                wikiDirRep.Add(new WikiDirectory(wDirData.DirectoryName, wDirData.ParentPath, userName));
                HttpContext.Session["__MyWorkingDir"] = new WorkingDirectory(Path.Combine(WikiRoot.RootDirectory, wDirData.ParentPath, wDirData.DirectoryName));
                string path = ((WorkingDirectory)this.GetMySessionObject("__MyWorkingDir")).WorkingDir;
                path = "~\\" + path.Substring(path.IndexOf(WikiRoot.RootDirectory));
                return RedirectToAction("Index", new { fullpath = path });
            }
            catch (SystemException ex)
            {
                Debug.Print(ex.Message);
                return View(wDirData);
            }
        }

        //
        // GET: /WikiDirectory/Edit/5
        [TopicActionFilter]
        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /WikiDirectory/Edit/5

        [HttpPost]
        [TopicActionFilter]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /WikiDirectory/Delete/5
        [TopicActionFilter]
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /WikiDirectory/Delete/5

        [HttpPost]
        [TopicActionFilter]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        [HttpPost]
        public ActionResult ListType(FormCollection fc)
        {
            if (fc["ListTypeSelected"] == "1") {
                return RedirectToAction("WikiTopicListing", "WikiDirectory", new { listType = "1" });
            }
            else {
                return RedirectToAction("WikiTopicListing", "WikiDirectory", new { listType = "2" });
            }
        }

        [TopicActionFilter]
        public ActionResult WikiTopicListing(string listType = "1")
        {
            WikiTopicListings topicList = new WikiTopicListings();
            topicList.ListTypeSelected = listType;
            topicList.Selections.Add(new ListTypeSelection { ID = 1, ListType = "All" });
            topicList.Selections.Add(new ListTypeSelection { ID = 2, ListType = "Recent Changes" });

            List<WikiTopicListingViewData> wtlvd = new List<WikiTopicListingViewData>();
            WikiDirectoryRepository wikiDirRep = new WikiDirectoryRepository(Server.MapPath(@"~\" + WikiRoot.RootDirectory), User);
            List<FileInfo> fi = wikiDirRep.GetWikiTopicFileInfoList();
            foreach (FileInfo file in fi) {
                WikiTopicListingViewData wtl = new WikiTopicListingViewData();
                wtl.WikiDir = WikiRoot.RootDirectory.Replace(@"\", "/");
                wtl.TopicName = file.Name.Substring(0, file.Name.IndexOf("_current.xml") - 1);
                wtl.CreatedOn = file.LastWriteTime;
                wtl.TopicLocked = wikiDirRep.TopicIsLocked(file.Name);
                wtlvd.Add(wtl);
            }
            IEnumerable<WikiDirectory> wdl = wikiDirRep.GetSubDirectoryList();
            foreach (WikiDirectory dir in wdl) {
                WikiDirectoryRepository wdr = new WikiDirectoryRepository(Server.MapPath(@"~\" + WikiRoot.RootDirectory + @"\" + dir.DirectoryName), User);
                fi = wdr.GetWikiTopicFileInfoList();
                foreach (FileInfo file in fi) {
                    WikiTopicListingViewData wtl = new WikiTopicListingViewData();
                    int start = file.FullName.IndexOf(WikiRoot.RootDirectory);
                    wtl.WikiDir = file.FullName.Substring(start, file.FullName.IndexOf(wdr.CurrentDir) + wdr.CurrentDir.Length - start).Replace(@"\","/");
                    wtl.TopicName = file.Name.Substring(0, file.Name.IndexOf("_current.xml") - 1);
                    wtl.CreatedOn = file.LastWriteTime;
                    wtl.TopicLocked = wdr.TopicIsLocked(file.Name);
                    wtlvd.Add(wtl);
                }
            }
            if (listType == "2") {
                wtlvd = wtlvd.OrderByDescending(l => l.CreatedOn).Take(15).ToList();
            }

            topicList.TopicListing = wtlvd;
            return View(topicList);
        }

        [TopicActionFilter]
        public ActionResult WikiTopicLockAction(string topicName, string wikiDir, string lockAction)
        {
            WikiDirectoryRepository wdr = new WikiDirectoryRepository(Server.MapPath(@"~\" + wikiDir));
            wdr.WikiTopicLockAction(topicName, lockAction);

            return RedirectToAction("WikiTopicListing");
        }

        [TopicActionFilter]
        public FileResult Export()
        {
            //ViewBag.CurrentDir = ((WorkingDirectory)this.GetMySessionObject("__MyWorkingDir")).WorkingDir;
            //WikiDirectoryRepository wdr = new WikiDirectoryRepository(Server.MapPath(ViewBag.CurrentDir), User);
            WikiDirectoryRepository wdr = new WikiDirectoryRepository(Server.MapPath(@"~\" + WikiRoot.RootDirectory), User);
            return File(wdr.ExportDirectoryToHtml(), System.Net.Mime.MediaTypeNames.Application.Zip);
        }
    }
}
